<?php
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Blovex4\Logic;

/**
 * 用户模型业务逻辑
 *
 * @author derek <693472824@qq.com>
 */
class AdminLogic extends BaseLogic {

    /**
     * 用户登录认证
     *
     * @param string $adminName
     *            用户名
     * @param string $password
     *            用户密码
     * @param integer $type
     *            用户名类型 （1-用户名，2-邮箱，3-手机，4-UID）
     * @return integer 登录成功-用户ID，登录失败-错误编号
     * @author derek <693472824@qq.com>
     */
    public function login ($adminName, $password, $type = 1) {
        $map = array();
        switch ($type) {
            case 1:
                $map['admin_account'] = (string)$adminName;
                break;
            case 2:
                $map['email'] = (string)$adminName;
                break;
            case 3:
                $map['mobile'] = (string)$adminName;
                break;
            case 4:
                $map['id'] = (string)$adminName;
                break;
            default:
                return 0; // 参数错误
        }
        
        /* 获取用户数据 */
        $admin = M('Admin')->where($map)->find();
        
        // 用户存在并且未禁止登录
        if (is_array($admin) && $admin['admin_status'] == 1) {
            
            /* 验证用户密码 */
            $data_auth_key = C('DATA_AUTH_KEY');
            if (think_ucenter_md5($password, $data_auth_key) === $admin['password']) {
                $this->updateLogin($admin['admin_id']);
                
                // 记录行为
                D('Action', 'Logic')->action_log('admin_login', 'admin', 
                        $admin['admin_id'], $admin['admin_id']);
                
                /* 记录登录SESSION和COOKIES */
                $auth = array(
                        'admin_id' => $admin['admin_id'],
                        'admin_name' => $admin['admin_name'],
                        'site_str' => $admin['site_id'],
                        'last_login_time' => $admin['last_login_time']
                );
                
                session('admin_auth', $auth);
                session('admin_auth_sign', data_auth_sign($auth));
                
                return $admin['admin_id'];
            } else {
                return - 2; // 密码错误
            }
        } else {
            return - 1; // 用户不存在或被禁用
        }
    }

    /**
     * 更新用户登录信息
     *
     * @param integer $uid
     *            用户ID
     * @author derek <693472824@qq.com>
     */
    protected function updateLogin ($uid)
    {
        $data = array(
                'admin_id' => $uid,
                'last_login_time' => NOW_TIME,
                'last_login_ip' => get_client_ip(1)
        );
        M('Admin')->save($data);
    }

    /**
     * 用户退出
     *
     * @author derek <693472824@qq.com>
     */
    public function logout ()
    {
        $adminID = AdminLogic::is_login();
        session('admin_auth', null);
        session('admin_auth_sign', null);
        session('ADMIN_MENU'.$adminID, null);
        session('ADMIN_MENU_LIST',null);
        session('ADMIN_MENU_TREE', null);
        S('DB_CONFIG_DATA', null);
    }

    /**
     * 判断用户是否登录
     *
     * @author derek <693472824@qq.com>
     */
    public static function is_login ()
    {
        $admin = session('admin_auth');
        if (empty($admin)) {
            return 0;
        } else {
            return session('admin_auth_sign') == data_auth_sign($admin) ? $admin['admin_id'] : 0;
        }
    }

    /**
     * 判断用户是否超级管理员
     *
     * @author derek <693472824@qq.com>
     */
    public static function is_admin ($admin_id = null)
    {
        $admin_id = is_null($admin_id) ? self::is_login() : $admin_id;
        return $admin_id && (intval($admin_id) == C('USER_ADMINISTRATOR'));
    }

    /**
     * 根据admin_id获取用户名
     *
     * @param integer $uid 用户ID
     * @author derek <693472824@qq.com>
     */
    public static function getAdminName ($uid)
    {
        $uid = empty($uid) || ! is_numeric($uid) ? self::is_login() : $uid;
        
        $map['admin_id'] = $uid;
        $admin_name = M('Admin')->where($map)->getField('admin_name');
        $admin_name = empty($admin_name) ? '' : $admin_name;
        
        return $admin_name;
    }
    
    /**
     * 获取当前用户 site_id 字段
     * @author derek <693472824@qq.com>
     */
    public static function getSite(){
        
        $admin = session('admin_auth');
        
        return empty($admin['site_str']) ? '0' : $admin['site_str'];
    }

    /**
     * 保存用户信息
     *
     * @author derek <693472824@qq.com>
     */
    public function saveAction() {
        $adminID = I('admin_id');
        $adminModel = D('Admin');

        if ($adminModel->create()) {
            
            if (empty($adminID)) {
                return $adminModel->add();
            } else {
                $map['admin_id'] = $adminID;
                return $adminModel->where($map)->save();
            }
        } else {
            $this->error = $adminModel->getError();
            return false;
        }
    }

    /**
     * 根据用户ID获取用户
     *
     * @param int $admin_id 用户id
     * @return object $adminModel 返回用户的一个模型
     * @author derek <693472824@qq.com>
     */
    public function getAdminByID ($admin_id)
    {
        if (empty($admin_id) || ! is_numeric($admin_id)) {
            return null;
        }
        
        $admin_where['admin_id'] = $admin_id;
        $admin_where['admin_status'] = '1';
        
        $adminModel = M('Admin')->where($admin_where)->find();
        
        return $adminModel;
    }

    /**
     * 用户删除
     *
     * @param array|int|string $admin_ids 用户ID
     * @return boolean true:代表成功 flase:代表失败
     * @author derek <693472824@qq.com>
     */
    public function del ($admin_ids){
        
        if (empty($admin_ids)) {
            return null;
        }else if(is_array($admin_ids)) {
                
            $admin_where['admin_id'] = array(
                    'in',
                    $admin_ids
            );
        }else{
            $admin_where['admin_id'] =  trim((string)$admin_ids, ',');
        }
        
        $result = M('Admin')->where($admin_where)->delete();
        
        return $result;
    }

    /**
     * 初始化用户密码
     * @param integer $admin_id 用户ID,$pwd 初始密码
     * @return boolean true:代表成功 flase:代表失败
     * @author derek <693472824@qq.com>
     */
    public function init_pwd ($admin_id) {
        
        if (empty($admin_id) || ! is_numeric($admin_id)) {
            return false;
        }
        
        $admin = D('Admin');
        $map['admin_id'] = $admin_id;
    
        $pwd_new = C('INIT_PWD') ? : 'admin123789';
        $data['admin_id'] = $admin_id;
        $data['password'] = $pwd_new;
    
        if ($admin->create($data)) {
            
            $result = $admin->save();
            return $result;
        }else{
            
            return false;
        }
    }
    
    /**
     * 修改密码
     *
     * @param int $adminid 用户ID |string $pwd 用户新密码
     * @author derek <693472824@qq.com>
     */
    public function updatePassword ($adminid, $password, $repassword){
        
        if (empty($adminid) || empty($password) || empty($repassword)) {
            return false;
        }
        
        $admin = D('Admin');
        
        $data['admin_id'] = $adminid;
        $data['password'] = $password;
        $data['repassword'] = $repassword;
        
        if ($admin->create($data, 4)) {
            
            $result = $admin->save();
            return $result;
        }else{
            
            $this->error = $admin->getError();
            return false;
        }
    }
    
    /**
     * 根据 admin_id 获取用户信息
     * 若参数为空，则获取全部用户
     * @param string|array  $adminID  用户ID字符串或数组
     * @return array|boolean $list   用户信息数组或错误
     * @author derek <693472824@qq.com>
     */
    public function getAdminListByID($adminID=array()){

        $list=null;
        $map = array();
        $adminID = is_string($adminID) ? trim($adminID, ',') : $adminID;
        
        if(!empty($adminID)){
            $map['admin_id'] = array('in', $adminID);
        }
        
        $list = M('Admin')->where($map)->select();
        
        return $list;
    }
    
}

?>